<template>
	<view class="pb-150">
		<!-- 导航栏 -->
		<image src="/static/dingbu.png" class="mine-navbar-bg" :style="{ height: navbarHeight + 'rpx' }" mode="aspectFill"></image>
		<u-navbar title="林业保护发展云讲堂" :autoBack="true" leftIconColor="#fff" bgColor="transparent"
			:titleStyle="{ color: '#fff' }" safeAreaInsetTop placeholder></u-navbar>

		<!-- 顶部筛选 -->
		<view class="search-filter-box">
			<view class="filter-row">
				<u-search v-model="query.keyword" placeholder="请输入课题/上传人" @search="onSearch"></u-search>
			</view>
			<view class="filter-row">
				<text class="filter-label">上传时间</text>
				<view class="date-inputs">
					<view class="date-input-wrapper" @click="showStartPicker = true">
						<u--input v-model="query.start" placeholder="开始日期" readonly :customStyle="{ height: '64rpx', fontSize: '16rpx', padding: '0 16rpx' }"></u--input>
						<u-icon name="calendar" size="16" color="#999" class="calendar-icon" />
					</view>
					<text class="date-separator">至</text>
					<view class="date-input-wrapper end" @click="showEndPicker = true">
						<u--input v-model="query.end" placeholder="结束日期" readonly :customStyle="{ height: '64rpx', fontSize: '16rpx', padding: '0 16rpx' }"></u--input>
						<u-icon name="calendar" size="16" color="#999" class="calendar-icon" />
					</view>
				</view>
			</view>
			<view class="filter-row">
				<view class="filter-item">
					<text class="filter-label">课件类别</text>
					<view class="picker-input" @click="showTypePicker = true">
						<text>{{ query.type || '全部' }}</text>
						<u-icon name="arrow-down" size="12" color="#999" />
					</view>
				</view>
			</view>
			<view class="action-buttons">
				<u-button type="primary" size="small" @click="onSearch"
					:customStyle="{ background: '#0A993B', borderColor: '#0A993B', color: '#fff' }">查询</u-button>
				<u-button size="small" @click="onReset" :customStyle="{ background: '#fff', borderColor: '#0A993B', color: '#0A993B' }">重置</u-button>
			</view>
		</view>

		<!-- 列表 -->
		<view class="list-wrap">
			<view class="card" v-for="(item, index) in filteredList" :key="index">
				<view class="card-hd">
					<view class="title">{{ item.title }}</view>
				</view>
				<view class="card-bd">
					<view class="row2">课件类别：{{ item.type }}</view>
					<view class="row2">课件标题：{{ item.title }}</view>
					<view class="row2 time">上传人：{{ item.uploader }}　上传时间：{{ item.time }}</view>
					<view class="row2">简介：{{ item.desc }}</view>
				</view>
				<u-button size="small" @click="onView(item)"
					:customStyle="{ background: '#0A993B', borderColor: '#0A993B', color: '#fff' }">查看</u-button>
			</view>
			<view v-if="filteredList.length === 0 && !loading" class="empty">
				<u-empty mode="data" icon="data"></u-empty>
			</view>
			<view v-if="loading" class="loading">
				<u-loading-icon mode="spinner" size="28"></u-loading-icon>
				<text class="loading-text">加载中...</text>
			</view>
			<view v-if="!hasMore && filteredList.length > 0" class="no-more">
				<text class="no-more-text">没有更多数据了</text>
			</view>
		</view>

		<!-- 选择器 -->
		<u-datetime-picker :show="showStartPicker" v-model="startTimestamp" mode="date" @confirm="onStartConfirm" @cancel="showStartPicker = false" @close="showStartPicker = false" />
		<u-datetime-picker :show="showEndPicker" v-model="endTimestamp" mode="date" @confirm="onEndConfirm" @cancel="showEndPicker = false" @close="showEndPicker = false" />
		<u-picker :show="showTypePicker" :columns="[typeOptions]" @confirm="onTypeConfirm" @cancel="showTypePicker = false" @close="showTypePicker = false" />
		<u-safe-bottom></u-safe-bottom>
	</view>
</template>

<script>
import navbarMixin from '@/common/navbarMixin'
import { getCoursewareType, getCoursewareList } from '@/api/economicforest'

export default {
	mixins: [navbarMixin],
			data() {
			return {
				query: { keyword:'', start:'', end:'', type:'' },
				showStartPicker:false, showEndPicker:false, showTypePicker:false,
				startTimestamp: Date.now(), // 开始日期时间戳
				endTimestamp: Date.now(), // 结束日期时间戳
				yearOptions:(()=>{ const y=new Date().getFullYear(); const r=[]; for(let i=y+2;i>=y-5;i--) r.push(i.toString()); return r })(),
				typeOptions:['全部','技术培训','防护知识','政策宣讲'],
				typeIdMap: {}, // 保存类型ID映射，用于API调用
				list:[],
				loading: false,
				pageNum: 1,
				pageSize: 10,
				hasMore: true
			}
		},
	computed:{
		filteredList(){
			return this.list
		}
	},
	async onLoad() {
		// 获取课件类型
		await this.getCoursewareTypes()
		// 获取课件列表
		await this.getCoursewareList()
	},
	methods:{
		// 获取课件类型
		async getCoursewareTypes() {
			try {
				const response = await getCoursewareType()
				console.log('课件类型数据:', response)

				if (response && response.data) {
					// 使用dictLabel作为显示名称
					const types = response.data.map(item => item.dictLabel || item.label || item.value)
					this.typeOptions = ['全部', ...types]
					
					// 保存类型ID映射，用于API调用
					this.typeIdMap = {}
					response.data.forEach(item => {
						const label = item.dictLabel || item.label || item.value
						this.typeIdMap[label] = item.dictValue || item.value
					})
				}
			} catch (error) {
				console.error('获取课件类型失败:', error)
			}
		},
		// 获取课件列表
		async getCoursewareList(isRefresh = false) {
			if (this.loading) return
			
			this.loading = true
			
			try {
				// 构建请求参数
				const params = {
					pageNum: isRefresh ? 1 : this.pageNum,
					pageSize: this.pageSize
				}
				
				// 添加搜索条件
				if (this.query.keyword && this.query.keyword.trim()) {
					params.query = this.query.keyword.trim()
				}
				
				// 添加课件类型
				if (this.query.type && this.query.type !== '全部') {
					// 使用dictValue而不是dictLabel
					params.coursewareType = this.typeIdMap[this.query.type] || this.query.type
				}
				
				// 添加时间范围
				if (this.query.start) {
					params.beginTime = this.query.start
				}
				if (this.query.end) {
					params.endTime = this.query.end
				}
				
				console.log('请求参数:', params)
				
				const response = await getCoursewareList(params)
				console.log('课件列表数据:', response)
				
				if (response && response.rows) {
					// 转换数据格式以匹配现有的显示结构
					const convertedData = response.rows.map(item => ({
						type: this.getTypeText(item.coursewareType),
						title: item.coursewareName || '未知标题',
						uploader: item.name || '未知用户',
						time: this.formatTime(item.createTime),
						desc: item.content || '暂无简介',
						// 保留原始数据用于详情页
						originalData: item
					}))
					
					if (isRefresh) {
						this.list = convertedData
						this.pageNum = 1
					} else {
						this.list = [...this.list, ...convertedData]
					}
					
					// 判断是否还有更多数据
					this.hasMore = response.rows.length === this.pageSize
					if (this.hasMore) {
						this.pageNum++
					}
				}
			} catch (error) {
				console.error('获取课件列表失败:', error)
				uni.showToast({
					title: '获取数据失败',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		},
		// 获取类型文本
		getTypeText(type) {
			const typeMap = {
				'1': '技术培训',
				'2': '防护知识', 
				'3': '政策宣讲'
			}
			return typeMap[type] || '未知类型'
		},
		// 格式化时间
		formatTime(timeStr) {
			if (!timeStr) return '未知时间'
			return timeStr.substring(0, 10) // 只取日期部分
		},
		async onSearch(){
			this.pageNum = 1
			await this.getCoursewareList(true)
		},
		async onReset(){ 
			this.query={ keyword:'', start:'', end:'', type:'' }
			this.startTimestamp = Date.now()
			this.endTimestamp = Date.now()
			this.pageNum = 1
			await this.getCoursewareList(true)
		},
		onStartConfirm(e){ 
			// u-datetime-picker 返回的是时间戳，需要转换为 YYYY-MM-DD 格式
			const timestamp = e?.value || e?.detail?.value || this.startTimestamp
			if (timestamp) {
				this.startTimestamp = timestamp // 同步更新时间戳
				const date = new Date(timestamp)
				const year = date.getFullYear()
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				this.query.start = `${year}-${month}-${day}`
			}
			this.showStartPicker = false 
		},
		onEndConfirm(e){ 
			// u-datetime-picker 返回的是时间戳，需要转换为 YYYY-MM-DD 格式
			const timestamp = e?.value || e?.detail?.value || this.endTimestamp
			if (timestamp) {
				this.endTimestamp = timestamp // 同步更新时间戳
				const date = new Date(timestamp)
				const year = date.getFullYear()
				const month = String(date.getMonth() + 1).padStart(2, '0')
				const day = String(date.getDate()).padStart(2, '0')
				this.query.end = `${year}-${month}-${day}`
			}
			this.showEndPicker = false 
		},
		onTypeConfirm(e){ 
			const selectedType = e.value[0]
			this.query.type = selectedType
			this.showTypePicker = false 
		},
		onView(item){
			// 跳转到详情页面，传递ID和原始数据
			const id = item.originalData?.id || item.id
			const dataToPass = item.originalData || item
			const q = encodeURIComponent(JSON.stringify(dataToPass))
			uni.navigateTo({ url: `/pages/workbench/07jingjilin/04detail?id=${id}&data=${q}` })
		},
		// 下拉刷新
		async onPullDownRefresh() {
			await this.getCoursewareList(true)
			uni.stopPullDownRefresh()
		},
		// 上拉加载更多
		async onReachBottom() {
			if (this.hasMore && !this.loading) {
				await this.getCoursewareList()
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.mine-navbar-bg { position: fixed; top: 0; left: 0; width: 750rpx;  z-index: 1; }
.search-filter-box { background: #fff; margin: 20rpx; padding: 20rpx; border-radius: 16rpx; box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.06); }
.filter-row { display: flex; align-items: center; gap: 16rpx; margin-bottom: 12rpx; }
.filter-item { display: flex; align-items: center; }
.filter-label { color: #666; font-size: 26rpx; }
.w-105 { width: 105rpx; }
.date-inputs { display: flex; align-items: center; flex: 1; gap: 12rpx; }
.date-input-wrapper { position: relative; flex: 1; }
.date-input-wrapper.end { flex: .9; }
.calendar-icon { position: absolute; right: 16rpx; top: 50%; transform: translateY(-50%); pointer-events: none; }
.date-separator { color: #999; font-size: 26rpx; }
.picker-input { min-width: 120rpx; flex: 1; display: flex; align-items: center; justify-content: space-between; background: #f8f9fa; padding: 14rpx; border-radius: 12rpx; color: #333; font-size: 26rpx; }
.action-buttons { display: flex; gap: 16rpx; margin-top: 6rpx; }
.action-buttons .u-button { flex: 1; }

.list-wrap { margin: 20rpx; }
.card { background: #fff; border-radius: 16rpx; padding: 16rpx; margin-bottom: 16rpx; box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.06); }
.card-hd { display: flex; align-items: center; justify-content: space-between; }
.title { font-size: 28rpx; font-weight: 600; color: #333; }
.card-bd { margin-top: 10rpx; color: #666; }
.row2 { font-size: 24rpx; margin: 10rpx 0; }
.time { color: #999; }
.empty { padding: 80rpx 0; }
.loading { display: flex; align-items: center; justify-content: center; padding: 40rpx 0; }
.loading-text { margin-left: 10rpx; color: #999; font-size: 26rpx; }
.no-more { text-align: center; padding: 40rpx 0; color: #999; font-size: 26rpx; }
</style>
